<?php

namespace App\Console\Commands;

use App\Models\Todolsit;
use Illuminate\Console\Command;
use Illuminate\Support\Str;

class ReadTodoList extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'todolist:read';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Read todo list from txt file.';

    /**
     * Create a new command instance.
     *
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $lines = $this->readFile();

        foreach ($lines as $line) {
            $bool = Todolsit::create([
                'desc' => $line,
            ]);

            if ($bool == true) {
                echo $line . ' 入库成功!' . PHP_EOL;
            }
        }
    }

    // 读取文件输出数组
    private function readFile()
    {
        $txtfile = base_path('todolist.txt');
        $result = [];
        $file = fopen($txtfile, 'rb');
        while (($line = fgets($file)) != feof($file)) {
            $result[] = trim($line);
        }

        return $result;
    }
}
